// ==UserScript==
// @name           eRep Party List Exporter
// @namespace      www.erepublik.com
// @description    Retrieves a complete list of party members
// @version        0.1
// @include        http://www.erepublik.com/en/party/*
// @require        http://code.jquery.com/jquery-latest.min.js
// ==/UserScript==

var partyList = new function() {
	var me		= this;
	
	this.cp		= 1;
	this.tp		= 1;
	this.list	= "";
	this.url	= "http://www.erepublik.com/en/party-members/"+window.location.href.split("/")[5]+"/";	
	
	this.members = new Array(); 
	
	this.pageList = function(p) {
		$.ajax({
			async: true,
			type: "GET",
			url: me.url + p,
			dataType: "html",
			success: function(html) {
				try {
					if (me.tp == 1) me.tp = $(html).find(".pager .last").attr("href").split("/")[4];
				} catch (c) {
				}

				window.status = "Loading page "+p+" of "+me.tp;
			
				$(html).find("a.nameholder").each(function(i) {
					me.members.push(cID = $(this).attr("href").split('/')[4]);
				});
				
				me.cp++;
				
				if (me.cp <= me.tp)
					me.pageList(me.cp);
				else
					me.getDatas();
			}
		});	
	}

	this.good = 0;
	this.bad = 0;
	this.getDatas = function() {
		GM_log('members:'+me.members.length);
		for(var i=0;i<me.members.length;i++) {
			GM_log('member '+i+','+me.members[i]);
			GM_xmlhttpRequest({
				method: "GET",
				url: "http://api.erepublik.com/v1/feeds/citizens/"+me.members[i],
				onerror: function(response) {
					me.bad++;
					GM_log('bad:'+me.bad);
				},
				onload: function(response) {
					me.good++;
					response.responseXML = new DOMParser().parseFromString(response.responseText, "text/xml");
					var w = $('citizen wellness',response.responseXML).text();
					var id = $('citizen > id',response.responseXML).text();
					var name = $('citizen > name',response.responseXML).text();
					var strength = $('citizen > strength',response.responseXML).text();
					GM_log('good:'+me.good+'w'+w+'id'+id);
					me.list += name+';'+id+';'+w+';'+strength+"\n";
					me.showResults();
				}
			})
		}
	}
	
	this.showResults = function() {
		if (me.bad+me.good==me.members.length) {
			$("<textarea></textarea>")
				.css({
					width: "400px",
					height: "150px",
					clear: "both"
				})
				.text(me.list)
				.appendTo(".indent:first")
				.show();
		}
	}
	
	$(document).ready(function() {		
		$('<span class="vround-btn-start goright"><span class="vround-btn-end"><a class="vround-btn-core" href="#">Export complete list</a></span></span>')
			.appendTo(".action:first")
			.click(function() {		
				me.pageList(1);
			});
	});
}
